package org.tzw.template.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.google.android.material.snackbar.Snackbar;

import org.tzw.template.R;
import org.tzw.template.logger.LocalLogger;
import org.tzw.template.utils.ActivityContainer;
import org.tzw.template.utils.PermissionManager;
import org.tzw.template.utils.Utils;

import java.lang.reflect.Method;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;

public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity {
    protected T mRoot;

    private boolean exitFlag;
    protected boolean isMainActivity = false;
    private PermissionManager permissionManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        this.onCreateBefore();

        super.onCreate(savedInstanceState);
        setContentView(getLayout());
        LocalLogger.init(this);
        //初始化应用相关权限
        permissionManager = PermissionManager.getInstance();
        //初始化Activity管理工具
        ActivityContainer.getInstance().addActivity(this);

        this.onCreateAfter();

        this.requestPermission();
    }

    private void requestPermission() {
        List<String> needPermissions = permissionManager.getNeedPermissions(this);
        if (!CollUtil.isEmpty(needPermissions)) {
            boolean checkPermissions = permissionManager.checkPermissions(needPermissions.toArray(new String[needPermissions.size()]));
            if (checkPermissions) {
                //初始化属性
                this.initProperty();
            }
        } else {
            //初始化属性
            this.initProperty();
        }
    }

    /**
     * 创建之前操作
     */
    protected void onCreateBefore() {
    }

    /**
     * 创建之后操作
     */
    protected void onCreateAfter() {
    }

    /**
     * 初始化属性
     */
    private void initProperty() {
        initData();
        initView();
        initListener();
        initService();
    }

    protected void initService() {

    }

    /**
     * 获取布局id
     */
    private View getLayout() {
        mRoot = initViewBinding();
        return mRoot.getRoot();
    }

    /**
     * 初始化变量及数据值
     */
    protected void initData() {

    }

    /**
     * 初始化控件的方法
     */
    protected abstract void initView();

    /**
     * 实现控件的监听事件
     */
    protected abstract void initListener();

    /**
     * 初始化viewBinding,如果觉得效率低,自己重写,返回自定初始化的ViewBinding
     */
    private T initViewBinding() {
        Class<?> aClass = Utils.getGenericClass(this.getClass());
        Method method = ReflectUtil.getMethod(aClass, "inflate", LayoutInflater.class);
        return ReflectUtil.invoke(null, method, getLayoutInflater());
    }

    protected void showToastShort(String message) {
        showToast(message, 0);
    }

    protected void showToastLong(String message) {
        showToast(message, 1);
    }

    /**
     * 吐司信息
     */
    private void showToast(String message, int time) {
        Toast.makeText(this, message, time == 0 ? Toast.LENGTH_SHORT : Toast.LENGTH_LONG).show();
    }

    protected void showSnackBarViewShort(View view, String message) {
        showSnackBarView(view, message, 0);
    }

    protected void showSnackBarViewLong(View view, String message) {
        showSnackBarView(view, message, 1);
    }

    /**
     * SnackBarView
     */
    private void showSnackBarView(View view, String message, int time) {
        Snackbar.make(view, message, time == 0 ? Snackbar.LENGTH_SHORT : Snackbar.LENGTH_LONG)
                .setAction("Action", null).show();
    }

    /**
     * 跳转网页
     *
     * @param url
     */
    protected void startToWebView(String url) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    /**
     * 携带参数跳转页面
     *
     * @param targetActivity 目标页面Activity
     * @param intent
     */
    protected void redirectToActivityWithParameters(Class targetActivity, Intent intent) {
        intent.setClass(this, targetActivity);
        startActivity(intent);
    }

    /**
     * 跳转新页面
     *
     * @param targetActivity 目标页面Activity
     */
    protected void redirectToActivity(Class targetActivity) {
        startActivity(new Intent(this, targetActivity));
    }

    /**
     * 判断有无网络方法
     *
     * @return
     */
    protected boolean isNetworkAvailable() {
        return Utils.isNetworkAvailable(this);
    }

    /**
     * 打印日志方法
     *
     * @param logs
     */
    protected void showLogs(String logs) {
        LocalLogger.i(getTagName(), logs);
    }

    protected String getTagName() {
        return this.getClass().getSimpleName();
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        String activityName = this.getClass().getSimpleName();
        Log.d(getTagName(), "onRequestPermissionsResult-------false------" + activityName + "----requestCode--" + requestCode + "---" + permissionManager.getRequestCode());
        if (requestCode == 10101) {
            if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
                startActivityForResult(intent, 2);
            }
        } else {
            if (requestCode == permissionManager.getRequestCode()) {
                if (!permissionManager.verifyPermissions(grantResults)) {
//                    ActivityUtils.getInstance().finishPage(this);
                    noPermissionManager(permissions);
                } else {
                    this.initProperty();
                }
            }
        }
    }

    /**
     * 无权限处理逻辑
     * @param permissions
     */
    protected void noPermissionManager(String[] permissions) {
        ActivityContainer.getInstance().finishPage(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) { // 处理返回按钮点击事件
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 双击返回键退出
     */
    @Override
    public void onBackPressed() {
        if (isMainActivity) {
            if (!exitFlag) {
                showToast(getString(R.string.common_exit_again), 0);
                exitFlag = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exitFlag = false;
                    }
                }, 2000);
            } else {
                ActivityContainer.getInstance().finishAllPage();
                finish();
            }
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        ActivityContainer.getInstance().finishPage(this);
        super.onDestroy();
    }
}
